package com.js.common.genid;

import com.js.common.service.IdGenRuleService;
import com.js.common.util.SnowFlakeUtil;
import com.js.core.util.SpringContextHelper;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.genid.GenId;

import java.util.Map;

/**
 * @author ygl
 * @create 2018-11-01
 * @DESCRIPTION
 * 自定义ID生成器
 **/
public class JsGenId implements GenId<String> {

    private Map<String,String> ruleMap;

    private Map<String,String> getRuleMap(){
        if (CollectionUtils.isEmpty(ruleMap)) {
            try {
                IdGenRuleService bean = SpringContextHelper.getBean(IdGenRuleService.class);
                ruleMap = bean.buildPrefixByTable();
            }catch (Exception e){
                return null;
            }
        }
        return ruleMap;

    }
    /**
     * 根据table表名或者column字段名，可自定义ID规则
     * @param table
     * @param column
     * @return
     */
    @Override
    public String genId(String table, String column) {

        long nextId = SnowFlakeUtil.getFlowIdInstance().nextId();

        Map<String, String> ruleMap = getRuleMap();
        if (ruleMap != null) {
            for (Map.Entry<String, String> entry : ruleMap.entrySet()) {
                String tableName = entry.getKey();
                if (!StringUtils.isEmpty(table)) {
                    if (tableName.equals(table)) {
                        String prefix = entry.getValue();
                        return prefix + nextId;
                    }
                }
            }
        }
        return ""+nextId;
    }
}
